package com.jsjosem.aftersales.ui.worktickets;

import static com.jsjosem.aftersales.utils.CommonUtils.showBigImg;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.ImgListViewAdapter;
import com.jsjosem.aftersales.adapter.ServiceItemsAdapter;
import com.jsjosem.aftersales.component.CustomGridView;
import com.jsjosem.aftersales.data.response.ImgResponse;
import com.jsjosem.aftersales.data.response.Product;
import com.jsjosem.aftersales.data.response.ProductResponse;
import com.jsjosem.aftersales.data.response.ServicesResponse;
import com.jsjosem.aftersales.data.response.WorkOrderReceiptResponse;
import com.jsjosem.aftersales.data.response.WorkOrderResponse;
import com.jsjosem.aftersales.data.response.WorkTicket;
import com.jsjosem.aftersales.utils.PageUtils;
import com.jsjosem.aftersales.utils.ViewUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ReceiptInfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ReceiptInfoFragment extends Fragment {

    private CustomGridView serviceBeforeImgGridView, serviceAfterImgGridView;
    private Context context;
    private WorkTicket workTicket;
    private View view;
    private TextView tvServicePerson;
    private TextView tvReceiptTime;
    private TextView tvProduct;
    private TextView tvProductSn;
    private TextView tvWarrantyStatus;
    private TextView tvFaultType;
    private TextView tvProcessMsg;
    private TextView tvComment;
    private ListView lvServiceItems;
    private ImageView ivSignature;
    private MaterialRatingBar rbarSatisfacation;
    private MaterialRatingBar rbarAttitude;
    private MaterialRatingBar rbarEfficiency;
    private List<ServicesResponse> servicesList=new ArrayList<>();
    private ServiceItemsAdapter serviceItemsAdapter;


    private ReceiptInfoFragment(WorkTicket workTicket) {
        this.workTicket = workTicket;
    }

    public static ReceiptInfoFragment newInstance(WorkTicket workTicket) {
        return new ReceiptInfoFragment(workTicket);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_receipt_info, container, false);
        context = view.getContext();
        initView();
        WorkOrderResponse originalTicket = workTicket.getOriginalTicket();
        List<Product> productResponses = originalTicket.getmProducts();
        if (CollUtil.isNotEmpty(productResponses)) {
            List<ProductResponse> products = productResponses.stream().map(Product::getProduct).collect(Collectors.toList());
//            String productText = products.stream().map(p -> String.format("%s (%s)", p.getmName(), p.getmModel())).collect(Collectors.joining(","));
            List<String> productList = new ArrayList<>();
            List<String> productNumList = new ArrayList<>();
            List<String> warrantyStatusList = new ArrayList<>();

            for (Product product : workTicket.getOriginalTicket().getmProducts()) {
                if (product.getProduct() != null) {
                    productList.add(product.getProduct().getmName());
                    productNumList.add(product.getProduct().getmProductNumber());
                    warrantyStatusList.add(product.getProduct().getmWarrantyStatusTitle());
                }
            }
            String productText=String.join(",", productList);
            String productNumber=String.join(",", productNumList);
            String warrantyStatus=String.join(",", warrantyStatusList);
            tvProduct.setText(productText);
//            String productNumber = products.stream().map(ProductResponse::getmProductNumber).collect(Collectors.joining(","));
            tvProductSn.setText(productNumber);
//            String warrantyStatus = products.stream().map(ProductResponse::getmWarrantyStatusTitle).collect(Collectors.joining(","));
            tvWarrantyStatus.setText(warrantyStatus);
        }
        WorkOrderReceiptResponse receipt = originalTicket.getmReceipt();
        tvServicePerson.setText(workTicket.getHandlers());
        tvFaultType.setText(originalTicket.getmDescription());
        tvProcessMsg.setText(receipt.getProcessType());
        tvComment.setText(receipt.getDescription());
        Glide.with(context)
                .load(receipt.getSignatureUrl())
                .placeholder(R.drawable.rotate_pro)
                .error(R.drawable.load_failed_24dp)
                .override(600, 400)
                .into(ivSignature);
        rbarSatisfacation.setProgress(receipt.getSatisfaction().intValue(), false);
        rbarAttitude.setProgress(receipt.getAttitude().intValue(), false);
        rbarEfficiency.setProgress(receipt.getEfficiency().intValue(), false);
        if (receipt.getmServices()!=null){
            servicesList.addAll(receipt.getmServices());
            serviceItemsAdapter.notifyDataSetChanged();
            ViewUtils.setListViewHeightBasedOnChildren(lvServiceItems);
        }
        return view;
    }

    private void initView() {
        tvServicePerson = view.findViewById(R.id.servicePersonTv);
        tvReceiptTime = view.findViewById(R.id.receiptTimeTv);
        tvProduct = view.findViewById(R.id.productTv);
        tvProductSn = view.findViewById(R.id.productSnTv);
        tvWarrantyStatus = view.findViewById(R.id.warrantyStatusTv);
        tvFaultType = view.findViewById(R.id.faultTypeTv);
        tvProcessMsg = view.findViewById(R.id.processMsgTv);
        tvComment = view.findViewById(R.id.commentTv);
        ivSignature = view.findViewById(R.id.iv_signature);
        rbarSatisfacation = view.findViewById(R.id.rbar_satisfaction);
        rbarSatisfacation.setMax(5);
        rbarAttitude = view.findViewById(R.id.rbar_attitude);
        rbarAttitude.setMax(5);
        rbarEfficiency = view.findViewById(R.id.rbar_efficiency);
        rbarEfficiency.setMax(5);
        serviceBeforeImgGridView = view.findViewById(R.id.serviceBeforeImgGridView);
        serviceAfterImgGridView = view.findViewById(R.id.serviceAfterImgGridView);
        lvServiceItems=view.findViewById(R.id.service_lv);
        serviceItemsAdapter=new ServiceItemsAdapter(context,R.layout.service_item_list,servicesList);
        lvServiceItems.setAdapter(serviceItemsAdapter);
        WorkOrderResponse workOrderResponse = workTicket.getOriginalTicket();
        List<ImgResponse> beforeImages = workOrderResponse.getmImages();
        if (CollUtil.isNotEmpty(beforeImages)) {
            List<String> imgUrls = beforeImages.stream().map(ImgResponse::getImg_url).collect(Collectors.toList());
            ImgListViewAdapter imgListViewAdapter2 = new ImgListViewAdapter(context, imgUrls);
            serviceBeforeImgGridView.setAdapter(imgListViewAdapter2);
            serviceBeforeImgGridView.setOnItemClickListener((adapterView, listView, position, id) -> {
                // 放大图片
                showBigImg(context, imgUrls, position);
            });
        }

        List<ImgResponse> afterImages = workOrderResponse.getmReceipt().getImages();
        if (CollUtil.isNotEmpty(afterImages)) {
            List<String> imgUrls = afterImages.stream().map(ImgResponse::getImage_url).collect(Collectors.toList());
            ImgListViewAdapter imgListViewAdapter = new ImgListViewAdapter(context, imgUrls);
            serviceAfterImgGridView.setAdapter(imgListViewAdapter);
            serviceAfterImgGridView.setOnItemClickListener((adapterView, listView, position, id) -> {
                // 放大图片
                showBigImg(context, imgUrls, position);
            });
        }
    }
}